<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // Promise.any( )  该方法接受一组 Promise 实例作为参数，包装成一个新的 Promise 实例返回。
    // var p = Promise.any([p1,p2,p3])

    // 只要参数实例有一个变成fulfilled状态，包装实例就会变成fulfilled状态；如果所有参数实例都变成rejected状态，包装实例就会变成rejected状态。 => 有一个成功就成功  全都失败才失败(results.errors)



    Promise.myAny = function (arr) {  //  [p1, p2, p3]
        return new Promise(function (resolve, reject) {

            // var arr = [p1, p2, p3];  //多个Promise对象放到数组中
            var count = 0;
            var list = [];
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];   // 每一个Promise对象
                item.then(arg => {
                    // list.push(arg); //  先有结果的先放  [2,1,3]

                    // then() catch() 方法中的回调函数 -> 需要等Promise对象状态改变之后 才会执行(异步) => 先执行主线程同步代码(i=3) => 等回调函数执行时 i = 3    
                    // 怎么解决?
                    // console.log("i", i);
                    resolve(arg);

                }).catch(err => {
                    count++;
                    list[i] = err;


                    // console.log(i, list);
                    // 等三个请求都成功之后  => 怎么把list传出去 (异步的基础上解决异步)
                    if (count === arr.length) {  //全都成功
                        var err = new AggregateError("All promises were rejected");
                        err.errors = list;
                        reject(err);
                    }
                })
            }
        })
    }
    
    var p1 = getNumAsync(1, 2000, false);
    var p2 = getNumAsync(2, 1000, false);
    var p3 = getNumAsync(3, 3000, false);

    // var p = Promise.myAny([p1, p2, p3]);
    var p = Promise.any([p1, p2, p3]);

    p.then(arg => {
        console.log("fulfilled", arg);
    }).catch(results => {
        console.log("rejected", results);
        console.log("rejected", results.errors);
    })



    function getNumAsync(num, delay = 0, isFulfilled = true) {
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                isFulfilled ? resolve(num) : reject(num);
            }, delay);
        });
        return p;
    }


</script>

</html>